package com.tzjw.marketweixin.exception;


import com.tzjw.marketweixin.exception.errorcode.CommonErrorCode;
import com.tzjw.marketweixin.pojo.vo.BaseRespVo;
import org.springframework.lang.Nullable;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * GlobalExceptionHandler 全局异常处理
 * @author hayden
 * @version 2023/09/17 09:45
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public BaseRespVo<Nullable> exceptionGet(HttpServletRequest req, HttpServletResponse response , Exception e) {
//		自定义异常类
		if (e instanceof CustomException) {
			CustomException be = (CustomException) e;
			if(CommonErrorCode.CUSTOM.equals(be.getErrorCode())){
				return new BaseRespVo<Nullable>(be.getErrorCode().getCode(), be.getMessage());
			}else{
				return new BaseRespVo<Nullable>(be.getErrorCode().getCode(), be.getErrorCode().getDesc());
			}

//		系统异常
		}else if(e instanceof NoHandlerFoundException){
			return new BaseRespVo<Nullable>(404, "找不到资源");
		}else if(e instanceof HttpRequestMethodNotSupportedException){
			return new BaseRespVo<Nullable>(405, "method 方法不支持");
		}else if(e instanceof HttpMediaTypeNotSupportedException){
			return new BaseRespVo<Nullable>(415, "不支持媒体类型");
		}

		e.printStackTrace();
//		log.error("【系统异常】" + e.getMessage());
		return  new BaseRespVo<Nullable>(CommonErrorCode.UNKNOW.getCode(), CommonErrorCode.UNKNOW.getDesc());
	}

}
